let upload = require('../../common/upload')
Page({
    behaviors: [upload],
    data: {
        supplierInfo: null, //上页传递的供应商信息
        goodInfo: null, //上页传递的商品信息
        reason: '',
        num: 1,
        numErr: false,
        refund_money_total: 0, //退款总金额，前端暂时计算
        voucher: [], //上传的凭证
        voucherFormData: { from: 'comment' },
        buttonLoading: false
    },
    onLoad: function(options) {
        const eventChannel = this.getOpenerEventChannel()
        eventChannel.on('acceptDataFromOpenerPage', ({ data }) => {
            this.setData({
                supplierInfo: data.supplierInfo,
                goodInfo: data.goodInfo,
                refund_money_total: Number(data.goodInfo.product_price)
            })
        })
    },
    /**输入退款数量失去焦点事件 */
    numBlur(e) {
        let { value } = e.detail
        value = parseInt(value)
        if (value > Number(this.data.goodInfo.product_number)) {
            this.setData({ num: '', refund_money_total: 0 })
            return wx.showToast({
                title: '最大可输入' + this.data.goodInfo.product_number,
                icon: 'none'
            })
        }
        this.setData({ num: value, refund_money_total: Number((Number(this.data.goodInfo.product_price) * value).toFixed(2)) })
    },
    submit() {
        const { goodInfo, reason, num, voucher } = this.data
        if (!parseInt(num)) return this.setData({ numErr: true })
        for (let i = 0; i < voucher.length; i++) {
            if (voucher[i].status !== 'done') return wx.showToast({
                title: '有图片正在上传或上传失败',
                icon: 'none'
            })
        }
        this.setData({ buttonLoading: true })
        let reqData = {
            order_id: goodInfo.order_id,
            order_product_id: goodInfo.order_product_id,
            refund_amount: goodInfo.product_price,
            refund_num: num
        }
        if (reason !== '') reqData.content = reason
        if (voucher.length > 0) {
            let photos = voucher.map(item => {
                return item.uploadPath
            })
            reqData.photos = photos.join(',')
        }
        this.request({
            url: '/api/order/refund',
            method: 'POST',
            data: reqData
        }, () => {
            wx.showToast({
                title: '申请成功',
                icon: 'success',
                mask: true
            })
            const eventChannel = this.getOpenerEventChannel()
            eventChannel.emit('markRefund')
            this.delay(() => {
                wx.navigateBack()
            })
        }, () => {
            this.setData({ buttonLoading: false })
        })
    }
})